package cn.springcloud.fix.demo.leecode;

public class Sort {

    public static void main(String[] args) {
        int[] arr = {51, 2, 33, 12, 100};
        System.out.println("冒泡排序");
//        bubbleSort(arr);
        System.out.println("选择排序");
//        selectSort(arr);
        System.out.println("快速排序");
        quickSort(arr, 0, arr.length - 1);
        for (int j : arr) {
            System.out.println(j);
        }
    }

    private static void quickSort(int[] arr, int low, int high) {
        if (low >= high) return;
        int left = low;
        int right = high;
        int key = arr[left];

        while (left < right) {
            //先从右往左找到比基准小的，覆盖到基准的位置
            while (left < right && arr[right] >= key) {
                right--;
            }
            arr[left] = arr[right];
            //再从左往右找到比基准大的，覆盖到刚才的 right 位置
            while (left < right && arr[left] <= key) {
                left++;
            }
            arr[right] = arr[left];
        }

        //基准归位
        arr[left] = key;

        quickSort(arr, low, left - 1);
        quickSort(arr, right + 1, high);
    }

    static void bubbleSort(int[] arr) {
        for (int i = 0; i < arr.length; i++) {
            for (int j = 0; j < arr.length - 1 - i; j++) {
                if (arr[j] > arr[j + 1]) {
                    int tmp = arr[j + 1];
                    arr[j + 1] = arr[j];
                    arr[j] = tmp;
                }
            }
        }
        for (int j : arr) {
            System.out.println(j);
        }
    }

    static void selectSort(int[] arr) {
        for (int i = 0; i < arr.length - 1; i++) {
            for (int j = i + 1; j < arr.length; j++) {
                if (arr[i] > arr[j]) {
                    int tmp = arr[i];
                    arr[i] = arr[j];
                    arr[j] = tmp;
                }
            }
        }
        for (int j : arr) {
            System.out.println(j);
        }
    }
}
